package com.ali.biofiletransfer;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class BIOFileTransferServer {
    public static void main(String[] args) {
        try {
            //构建监听服务并绑定监听端口
            ServerSocket serverSocket = new ServerSocket(8080);
            while (true) {
                System.out.println("等待客户端连接");
                //获取客户端连接
                Socket socket = serverSocket.accept();
                System.out.println("接收客户端连接");
                long startTime = System.currentTimeMillis();
                long total = handle(socket);
                long endTime = System.currentTimeMillis();
                System.out.println("耗时：" + (endTime - startTime) + "，接收字节数：" + total);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 处理客户端连接
     */
    private static long handle(Socket socket) throws IOException {
        byte[] bytes = new byte[1024];
        int length;
        long total = 0;
        //构建文件输出流
        //获取输入流
        try (FileOutputStream fileOutputStream = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\testCopy.mobi"); InputStream inputStream = socket.getInputStream()) {
            while (true) {
                //写入内容至缓冲区
                length = inputStream.read(bytes);
                if (length > 0) {
                    //写入内容至文件输出流
                    fileOutputStream.write(bytes, 0, length);
                    total = total + length;
                } else if (length == 0) {
                    break;
                } else if (length == -1) {
                    System.out.println("客户端断开连接");
                    break;
                }
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return total;
    }
}
